<!DOCTYPE HTML>
<html lang="zh-CN">


<head>
    <meta charset="utf-8">
    <meta name="keywords" content="连通图的最小生成树算法, 大虫のBlog">
    <meta name="description" content="电子科技大学 | 信软学院 | 软件工程">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no">
    <meta name="renderer" content="webkit|ie-stand|ie-comp">
    <meta name="mobile-web-app-capable" content="yes">
    <meta name="format-detection" content="telephone=no">
    <meta name="apple-mobile-web-app-capable" content="yes">
    <meta name="apple-mobile-web-app-status-bar-style" content="black-translucent">
    <!-- Global site tag (gtag.js) - Google Analytics -->


    <title>连通图的最小生成树算法 | 大虫のBlog</title>
    <link rel="icon" type="image/png" href="/favicon.png">

    <link rel="stylesheet" type="text/css" href="/libs/awesome/css/all.css">
    <link rel="stylesheet" type="text/css" href="/libs/materialize/materialize.min.css">
    <link rel="stylesheet" type="text/css" href="/libs/aos/aos.css">
    <link rel="stylesheet" type="text/css" href="/libs/animate/animate.min.css">
    <link rel="stylesheet" type="text/css" href="/libs/lightGallery/css/lightgallery.min.css">
    <link rel="stylesheet" type="text/css" href="/css/matery.css">
    <link rel="stylesheet" type="text/css" href="/css/my.css">

    <script src="/libs/jquery/jquery.min.js"></script>

<meta name="generator" content="Hexo 6.2.0"></head>




<body>
    <header class="navbar-fixed">
    <nav id="headNav" class="bg-color nav-transparent">
        <div id="navContainer" class="nav-wrapper container">
            <div class="brand-logo">
                <a href="/" class="waves-effect waves-light">
                    
                    <img src="/medias/logo.png" class="logo-img" alt="LOGO">
                    
                    <span class="logo-span">大虫のBlog</span>
                </a>
            </div>
            

<a href="#" data-target="mobile-nav" class="sidenav-trigger button-collapse"><i class="fas fa-bars"></i></a>
<ul class="right nav-menu">
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/" class="waves-effect waves-light">
      
      <i class="fas fa-home" style="zoom: 0.6;"></i>
      
      <span>首页</span>
    </a>
    
  </li>
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/tags" class="waves-effect waves-light">
      
      <i class="fas fa-tags" style="zoom: 0.6;"></i>
      
      <span>标签</span>
    </a>
    
  </li>
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/categories" class="waves-effect waves-light">
      
      <i class="fas fa-bookmark" style="zoom: 0.6;"></i>
      
      <span>分类</span>
    </a>
    
  </li>
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/archives" class="waves-effect waves-light">
      
      <i class="fas fa-archive" style="zoom: 0.6;"></i>
      
      <span>归档</span>
    </a>
    
  </li>
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/about" class="waves-effect waves-light">
      
      <i class="fas fa-user-circle" style="zoom: 0.6;"></i>
      
      <span>关于</span>
    </a>
    
  </li>
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/contact" class="waves-effect waves-light">
      
      <i class="fas fa-comments" style="zoom: 0.6;"></i>
      
      <span>留言板</span>
    </a>
    
  </li>
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/friends" class="waves-effect waves-light">
      
      <i class="fas fa-address-book" style="zoom: 0.6;"></i>
      
      <span>友情链接</span>
    </a>
    
  </li>
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="" class="waves-effect waves-light">

      
      <i class="fa fa-list" style="zoom: 0.6;"></i>
      
      <span>其他</span>
      <i class="fas fa-chevron-down" aria-hidden="true" style="zoom: 0.6;"></i>
    </a>
    <ul class="sub-nav menus_item_child ">
      
      <li>
        <a target="_blank" rel="noopener" href="https://console.leancloud.cn">
          
          <i class="fa-solid fa-link" style="margin-top: -20px; zoom: 0.6;"></i>
          
          <span>LeanCloud 应用</span>
        </a>
      </li>
      
      <li>
        <a target="_blank" rel="noopener" href="https://www.tidio.com/panel">
          
          <i class="fa-solid fa-link" style="margin-top: -20px; zoom: 0.6;"></i>
          
          <span>TIDIO 聊天系统</span>
        </a>
      </li>
      
      <li>
        <a target="_blank" rel="noopener" href="https://www.coderutil.com">
          
          <i class="fa-solid fa-link" style="margin-top: -20px; zoom: 0.6;"></i>
          
          <span>CoderUtil 工具</span>
        </a>
      </li>
      
    </ul>
    
  </li>
  
  <li>
    <a href="#searchModal" class="modal-trigger waves-effect waves-light">
      <i id="searchIcon" class="fas fa-search" title="搜索" style="zoom: 0.85;"></i>
    </a>
  </li>
</ul>


<div id="mobile-nav" class="side-nav sidenav">

    <div class="mobile-head bg-color">
        
        <img src="/medias/logo.png" class="logo-img circle responsive-img">
        
        <div class="logo-name">大虫のBlog</div>
        <div class="logo-desc">
            
            电子科技大学 | 信软学院 | 软件工程
            
        </div>
    </div>

    

    <ul class="menu-list mobile-menu-list">
        
        <li class="m-nav-item">
	  
		<a href="/" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-home"></i>
			
			首页
		</a>
          
        </li>
        
        <li class="m-nav-item">
	  
		<a href="/tags" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-tags"></i>
			
			标签
		</a>
          
        </li>
        
        <li class="m-nav-item">
	  
		<a href="/categories" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-bookmark"></i>
			
			分类
		</a>
          
        </li>
        
        <li class="m-nav-item">
	  
		<a href="/archives" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-archive"></i>
			
			归档
		</a>
          
        </li>
        
        <li class="m-nav-item">
	  
		<a href="/about" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-user-circle"></i>
			
			关于
		</a>
          
        </li>
        
        <li class="m-nav-item">
	  
		<a href="/contact" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-comments"></i>
			
			留言板
		</a>
          
        </li>
        
        <li class="m-nav-item">
	  
		<a href="/friends" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-address-book"></i>
			
			友情链接
		</a>
          
        </li>
        
        <li class="m-nav-item">
	  
		<a href="javascript:;">
			
				<i class="fa-fw fa fa-list"></i>
			
			其他
			<span class="m-icon"><i class="fas fa-chevron-right"></i></span>
		</a>
            <ul  style="background:  ;" >
              
                <li>

                  <a target="_blank" rel="noopener" href="https://console.leancloud.cn " style="margin-left:75px">
				  
				   <i class="fa fa-solid fa-link" style="position: absolute;left:50px" ></i>
			      
		          <span>LeanCloud 应用</span>
                  </a>
                </li>
              
                <li>

                  <a target="_blank" rel="noopener" href="https://www.tidio.com/panel " style="margin-left:75px">
				  
				   <i class="fa fa-solid fa-link" style="position: absolute;left:50px" ></i>
			      
		          <span>TIDIO 聊天系统</span>
                  </a>
                </li>
              
                <li>

                  <a target="_blank" rel="noopener" href="https://www.coderutil.com " style="margin-left:75px">
				  
				   <i class="fa fa-solid fa-link" style="position: absolute;left:50px" ></i>
			      
		          <span>CoderUtil 工具</span>
                  </a>
                </li>
              
            </ul>
          
        </li>
        
        
        <li><div class="divider"></div></li>
        <li>
            <a href="https://gitee.com/yczlab" class="waves-effect waves-light" target="_blank">
                <i class="fab fa-github-square fa-fw"></i>Fork Me
            </a>
        </li>
        
    </ul>
</div>


        </div>

        
            <style>
    .nav-transparent .github-corner {
        display: none !important;
    }

    .github-corner {
        position: absolute;
        z-index: 10;
        top: 0;
        right: 0;
        border: 0;
        transform: scale(1.1);
    }

    .github-corner svg {
        color: #0f9d58;
        fill: #fff;
        height: 64px;
        width: 64px;
    }

    .github-corner:hover .octo-arm {
        animation: a 0.56s ease-in-out;
    }

    .github-corner .octo-arm {
        animation: none;
    }

    @keyframes a {
        0%,
        to {
            transform: rotate(0);
        }
        20%,
        60% {
            transform: rotate(-25deg);
        }
        40%,
        80% {
            transform: rotate(10deg);
        }
    }
</style>

<a href="https://gitee.com/yczlab" class="github-corner tooltipped hide-on-med-and-down" target="_blank"
   data-tooltip="Fork Me" data-position="left" data-delay="50">
    <svg viewBox="0 0 250 250" aria-hidden="true">
        <path d="M0,0 L115,115 L130,115 L142,142 L250,250 L250,0 Z"></path>
        <path d="M128.3,109.0 C113.8,99.7 119.0,89.6 119.0,89.6 C122.0,82.7 120.5,78.6 120.5,78.6 C119.2,72.0 123.4,76.3 123.4,76.3 C127.3,80.9 125.5,87.3 125.5,87.3 C122.9,97.6 130.6,101.9 134.4,103.2"
              fill="currentColor" style="transform-origin: 130px 106px;" class="octo-arm"></path>
        <path d="M115.0,115.0 C114.9,115.1 118.7,116.5 119.8,115.4 L133.7,101.6 C136.9,99.2 139.9,98.4 142.2,98.6 C133.8,88.0 127.5,74.4 143.8,58.0 C148.5,53.4 154.0,51.2 159.7,51.0 C160.3,49.4 163.2,43.6 171.4,40.1 C171.4,40.1 176.1,42.5 178.8,56.2 C183.1,58.6 187.2,61.8 190.9,65.4 C194.5,69.0 197.7,73.2 200.1,77.6 C213.8,80.2 216.3,84.9 216.3,84.9 C212.7,93.1 206.9,96.0 205.4,96.6 C205.1,102.4 203.0,107.8 198.3,112.5 C181.9,128.9 168.3,122.5 157.7,114.1 C157.9,116.9 156.7,120.9 152.7,124.9 L141.0,136.5 C139.8,137.7 141.6,141.9 141.8,141.8 Z"
              fill="currentColor" class="octo-body"></path>
    </svg>
</a>
        
    </nav>

</header>

    



<div class="bg-cover pd-header post-cover" style="background-image: url('/medias/featureimages/19.jpg')">
    <div class="container" style="right: 0px;left: 0px;">
        <div class="row">
            <div class="col s12 m12 l12">
                <div class="brand">
                    <h1 class="description center-align post-title">连通图的最小生成树算法</h1>
                </div>
            </div>
        </div>
    </div>
</div>




<main class="post-container content">

    
    <link rel="stylesheet" href="/libs/tocbot/tocbot.css">
<style>
    #articleContent h1::before,
    #articleContent h2::before,
    #articleContent h3::before,
    #articleContent h4::before,
    #articleContent h5::before,
    #articleContent h6::before {
        display: block;
        content: " ";
        height: 100px;
        margin-top: -100px;
        visibility: hidden;
    }

    #articleContent :focus {
        outline: none;
    }

    .toc-fixed {
        position: fixed;
        top: 64px;
    }

    .toc-widget {
        width: 345px;
        padding-left: 20px;
    }

    .toc-widget .toc-title {
        padding: 35px 0 15px 17px;
        font-size: 1.5rem;
        font-weight: bold;
        line-height: 1.5rem;
    }

    .toc-widget ol {
        padding: 0;
        list-style: none;
    }

    #toc-content {
        padding-bottom: 30px;
        overflow: auto;
    }

    #toc-content ol {
        padding-left: 10px;
    }

    #toc-content ol li {
        padding-left: 10px;
    }

    #toc-content .toc-link:hover {
        color: #42b983;
        font-weight: 700;
        text-decoration: underline;
    }

    #toc-content .toc-link::before {
        background-color: transparent;
        max-height: 25px;

        position: absolute;
        right: 23.5vw;
        display: block;
    }

    #toc-content .is-active-link {
        color: #42b983;
    }

    #floating-toc-btn {
        position: fixed;
        right: 15px;
        bottom: 76px;
        padding-top: 15px;
        margin-bottom: 0;
        z-index: 998;
    }

    #floating-toc-btn .btn-floating {
        width: 48px;
        height: 48px;
    }

    #floating-toc-btn .btn-floating i {
        line-height: 48px;
        font-size: 1.4rem;
    }
</style>
<div class="row">
    <div id="main-content" class="col s12 m12 l9">
        <!-- 文章内容详情 -->
<div id="artDetail">
    <div class="card">
        <div class="card-content article-info">
            <div class="row tag-cate">
                <div class="col s7">
                    
                    <div class="article-tag">
                        
                            <a href="/tags/Java/">
                                <span class="chip bg-color">Java</span>
                            </a>
                        
                            <a href="/tags/Algorithm/">
                                <span class="chip bg-color">Algorithm</span>
                            </a>
                        
                            <a href="/tags/DataStructure/">
                                <span class="chip bg-color">DataStructure</span>
                            </a>
                        
                    </div>
                    
                </div>
                <div class="col s5 right-align">
                    
                    <div class="post-cate">
                        <i class="fas fa-bookmark fa-fw icon-category"></i>
                        
                            <a href="/categories/Algorithm/" class="post-category">
                                Algorithm
                            </a>
                        
                    </div>
                    
                </div>
            </div>

            <div class="post-info">
                
                <div class="post-date info-break-policy">
                    <i class="far fa-calendar-minus fa-fw"></i>发布日期:&nbsp;&nbsp;
                    2021-01-21
                </div>
                

                
                <div class="post-date info-break-policy">
                    <i class="far fa-calendar-check fa-fw"></i>更新日期:&nbsp;&nbsp;
                    2022-07-31
                </div>
                

                
                <div class="info-break-policy">
                    <i class="far fa-file-word fa-fw"></i>文章字数:&nbsp;&nbsp;
                    4k
                </div>
                

                
                <div class="info-break-policy">
                    <i class="far fa-clock fa-fw"></i>阅读时长:&nbsp;&nbsp;
                    16 分
                </div>
                

                
                    <div id="busuanzi_container_page_pv" class="info-break-policy">
                        <i class="far fa-eye fa-fw"></i>阅读次数:&nbsp;&nbsp;
                        <span id="busuanzi_value_page_pv"></span>
                    </div>
				
            </div>
        </div>
        <hr class="clearfix">

        
        <!-- 是否加载使用自带的 prismjs. -->
        <link rel="stylesheet" href="/libs/prism/prism.css">
        

        

        <div class="card-content article-card-content">
            <div id="articleContent">
                <p>  </p>
<h2 id="引言："><a href="#引言：" class="headerlink" title="引言："></a>引言：</h2><blockquote>
<p>在线性表中，数据元素之间是被串起来的，仅有线性关系，每个数据元素只有一个直接前驱和一个直接后继。在树形结构中，数据元素之间有着明显的层次关系，并且每一层上的数据元素可能和下一层中多个元素相关，但只能和上一层中一个元素想关。这和一对父母可以有多个孩子，但每个孩子却只能有一对父母是一个道理。可现实中，人与人之间关系就非常复杂，比如我认识的朋友，可能他们之间也相互认识，这就不是简单的一对一、一对多的关系，研究人际关系很自然就会考虑到多对多的情况。也就是这篇博客的主题——图。图是一种较线性表和树更加复杂的数据结构。在图形结构中，节点之间的关系可以是任意的，图中任意两个数据元素之间都可能相关。</p>
</blockquote>
<h3 id="一、图的相关定义"><a href="#一、图的相关定义" class="headerlink" title="一、图的相关定义"></a>一、图的相关定义</h3><h4 id="1、图："><a href="#1、图：" class="headerlink" title="1、图："></a>1、图：</h4><p>  图（Grap）是由顶点<strong>的有穷非空集合</strong>和<strong>顶点之间的边集合</strong>组成，通常表示为：G（V,E），其中，G表示一个图；V是图G中顶点的集合；E是图G中边的集合。</p>
<blockquote>
<ul>
<li>通常线性表中我们把数据元素叫做元素，树中将数据元素叫做结点，<strong>在图中数据元素，则称之为顶点（Vertex）</strong>。</li>
<li>线性表中可以没有数据元素，称为<strong>空表</strong>。树中可以没有结点，叫做<strong>空树</strong>。但是在图结构中，不允许没有顶点。在定义中，若 V 是顶点的集合，则强调了顶点集合 V 有穷非空。</li>
<li>在线性表中，相邻的数据元素之间具有线性关系；在树结构中，相邻两层的结点具有层次关系。而在图中，<strong>任意两个顶点之间都可能有关系，顶点之间的逻辑关系用边来表示，边集可以是空的</strong>。</li>
</ul>
</blockquote>
<h4 id="2、无向边："><a href="#2、无向边：" class="headerlink" title="2、无向边："></a>2、无向边：</h4><blockquote>
<table>
<thead>
<tr>
<th>示意图</th>
<th>说明</th>
</tr>
</thead>
<tbody><tr>
<td><img src="/posts/4a73b033/1.png"></td>
<td>若顶点 V<sub>i</sub> 到 V<sub>j</sub> 之间的边没有方向，则称这条边为<strong>无向边（Edge）</strong>，用无序偶对（V<sub>i</sub>,V<sub>j</sub>）来表示。如果图中任意两个顶点之间的边都是无向边，则称该图为<strong>无向图</strong>。左侧就是一个无向图，由于是无方向的，连接顶点A与D的边，可以表示成无序对（A,D），也可以写成（D,A）。</td>
</tr>
</tbody></table>
</blockquote>
<h4 id="3、有向边："><a href="#3、有向边：" class="headerlink" title="3、有向边："></a>3、有向边：</h4><blockquote>
<table>
<thead>
<tr>
<th>示意图</th>
<th>说明</th>
</tr>
</thead>
<tbody><tr>
<td><img src="/posts/4a73b033/2.png"></td>
<td>若从顶点 V<sub>i</sub> 到 V<sub>j</sub> 之间的边有方向，则这条边为有向边，也称为<strong>弧（Arc）</strong>。用有序偶&lt;V<sub>i</sub>,V<sub>j</sub>&gt;来表示，V<sub>i</sub>称为弧尾（Tail），V<sub>j</sub>称为弧头（Head）。如果图中任意两个顶点之间的边都是有向边，则称该图为<strong>有向图</strong>。左图就是一个有向图，连接顶点A到D的有向边就是弧，A是弧尾，D是弧头，&lt;A,D&gt;表示该弧，不能写成&lt;D,A&gt;</td>
</tr>
</tbody></table>
</blockquote>
<h4 id="4、简单图："><a href="#4、简单图：" class="headerlink" title="4、简单图："></a>4、简单图：</h4><blockquote>
<ul>
<li>在图中，若不存在顶点到其自身的边，且同一条边不重复出现，则称这样的图为简单图。</li>
</ul>
</blockquote>
<h4 id="5、完全图："><a href="#5、完全图：" class="headerlink" title="5、完全图："></a>5、完全图：</h4><blockquote>
<ul>
<li>在无向图中，如果任意两个顶点之间都存在边，则称该图为无向完全图。含有n个顶点的无向完全图有n*(n-1)&#x2F;2条边。</li>
<li>在有向图中，如果任意两个顶点之间都存在方向互为相反的两条弧，则称该图为有向完全图。含有n个顶点的有向完全图有n*(n-1)条边。</li>
<li><strong>这里可以得出结论，对于具有n个顶点和e条边数的图，无向图 0≤e≤n(n-1)&#x2F;2，有向图 0≤e≤n(n-1)</strong></li>
</ul>
</blockquote>
<h4 id="6、网（带权图）"><a href="#6、网（带权图）" class="headerlink" title="6、网（带权图）"></a>6、网（带权图）</h4><blockquote>
<p>有些图的边或者弧具有与它相关的数字，这种与图的边或弧相关的数叫做<strong>权（Weight）。</strong>这些权可以表示从一个顶点到另一个顶点的距离或耗费。<strong>这种带权的图通常称为网</strong>。</p>
</blockquote>
<h4 id="7、子图"><a href="#7、子图" class="headerlink" title="7、子图"></a>7、子图</h4><blockquote>
<table>
<thead>
<tr>
<th>示意图</th>
<th>说明</th>
</tr>
</thead>
<tbody><tr>
<td><img src="/posts/4a73b033/3.png"></td>
<td>假设有两个图 G &#x3D; (V,{E})和 G<sup>‘</sup> &#x3D; (V<sup>‘</sup>,{E<sup>‘</sup>})，如果V<sup>‘</sup>∈V且E<sup>‘</sup>∈E，则称G<sup>‘</sup>为G的子图。例如左侧所示的有向图和无向图的子图。</td>
</tr>
</tbody></table>
</blockquote>
<h4 id="8、图的顶点与边之间的关系"><a href="#8、图的顶点与边之间的关系" class="headerlink" title="8、图的顶点与边之间的关系"></a>8、图的顶点与边之间的关系</h4><p><strong>对于无向图：</strong><br>  无向图 G &#x3D; (V,{E})，如果边(V,V<sup>‘</sup>)∈E，则称顶点V和V<sup>‘</sup>互为邻接点（Adjacent），即V和V<sup>‘</sup>相邻接。边(V,V<sup>‘</sup>)依附（incident）于顶点V和V<sup>‘</sup>，或者说(V,V<sup>‘</sup>)与顶点V和V<sup>‘</sup>相关联。<strong>顶点V的度（Degree）</strong>是和V相关联的边的数目，记为 <strong>TD(V)<strong>。如上图A与B互为邻接点，边（A,B）依附于顶点A与B上，顶点A的度为3。</strong>其实边数就是各顶点度数和的一半，多出的一半是因为重复计数了。</strong></p>
<p><strong>对于有向图：</strong><br>  有向图 G &#x3D; (V,{E})，如果弧&lt;V,V<sup>‘</sup>&gt;∈E，则称顶点V邻接到顶点V<sup>‘</sup>，顶点V<sup>‘</sup>邻接自顶点V。弧&lt;V,V<sup>‘</sup>&gt;和顶点V，V<sup>‘</sup>相关联。以顶点v为头的弧的数目称为V的<strong>入度</strong>，记为 ID(V)；以V为尾的弧的数目称为V的<strong>出度</strong>，记为OD(V)；顶点V的度为TD(V)&#x3D;ID(V)+OD(V)。<strong>其实边数就是各顶点的出度和，也是各顶点的入度和。</strong></p>
<h4 id="9、路径和环"><a href="#9、路径和环" class="headerlink" title="9、路径和环"></a>9、路径和环</h4><p>  无向图 G &#x3D; (V,{E}) 中从顶点V到顶点V<sup>‘</sup>的路径是一个顶点序列(V&#x3D;V<sub>i,0</sub>,V<sub>i,1</sub>······V<sub>i,m</sub>&#x3D;V<sup>‘</sup>)，其中(V<sub>i,j-1</sub>,V<sub>i,j</sub>)∈E，1≤j≤m。如果 G 是有向图，则路径也是有向的，顶点序列应满足&lt;V<sub>i,j-1</sub>,V<sub>i,j</sub>&gt;∈E，1≤j≤m。<br>  <strong>树中根结点到任意结点的路径是唯一的，但是图中顶点与顶点之间的路径却是不唯一的。</strong>路径的长度是路径上的边或弧的数目。第一个顶点到最后一个顶点相同的路径称为<strong>回路</strong>或<strong>环</strong>。序列中顶点不重复出现的路径称为<strong>简单路径</strong>。除了第一个顶点和最后一个顶点之外，其余顶点不重复出现的回路，称为<strong>简单回路</strong>或<strong>简单环</strong>。<br><img src="/posts/4a73b033/4.png" alt="左侧是简单环，右侧不是简单环"></p>
<h4 id="10、连通图相关术语"><a href="#10、连通图相关术语" class="headerlink" title="10、连通图相关术语"></a>10、连通图相关术语</h4><h5 id="无向图中"><a href="#无向图中" class="headerlink" title="无向图中"></a>无向图中</h5><p>  在无向图 G 中，如果从顶点V到顶点V<sup>‘</sup>有路径，则称<strong>V和V<sup>‘</sup>是连通的</strong>。如果对于图中任意两个顶点V<sub>i</sub>、V<sub>j</sub>∈V，V<sub>i</sub>和V<sub>j</sub>都是连通的，则称 G 是<strong>连通图</strong>。<strong>无向图中的极大连通子图称为连通分量</strong>。连通分量强调：</p>
<blockquote>
<ul>
<li>要是子图；</li>
<li>子图要是连通的；</li>
<li>连通子图含有极大顶点数；</li>
<li>具有极大顶点数的连通子图包含依附于这些顶点的所有边。</li>
</ul>
</blockquote>
<h5 id="有向图中"><a href="#有向图中" class="headerlink" title="有向图中"></a>有向图中</h5><p>  在有向图 G 中，如果对于每一对V<sub>i</sub>、V<sub>j</sub>∈V、V<sub>i</sub>≠V<sub>j</sub>，从V<sub>i</sub>到V<sub>j</sub>和从V<sub>j</sub>到V<sub>i</sub>都存在路径，则称 G 是<strong>强连通图</strong>。<strong>有向图中的极大强连通子图称做有向图的强连通分量。</strong></p>
<h4 id="11、连通图的生成树"><a href="#11、连通图的生成树" class="headerlink" title="11、连通图的生成树"></a>11、连通图的生成树</h4><p>  所谓的一个连通图的生成树是一个极小的连通子图，它含有图中全部的 n 个顶点，但只有足以构成一棵树的 n-1 条边。如果一个图有 n 个顶点和小于 n-1 条边，则该图是非连通图。如果它有多于 n-1 条边，则必定构成一个环，因为这条边使得它依附的那两个顶点之间有了第二条路径。不过有 n-1 条边，并不一定是生成树。<br>  如果一个有向图恰好有一个顶点的入度为0，其余顶点的入度均为1，则是一颗有向树。对有向树的理解比较容易，所谓入度为0其实就相当于树中的根结点，其余顶点入度为1就是说树的非根节点的双亲只有一个。一个有向图的生成森林由若干棵有向树组成，含有图中全部顶点，但是有足以构成若干棵不相交的有向弧。</p>
<h4 id="12、图的定义与术语总结"><a href="#12、图的定义与术语总结" class="headerlink" title="12、图的定义与术语总结"></a>12、图的定义与术语总结</h4><ol>
<li><strong>图</strong>按照有无方向分为<strong>无向图</strong>和<strong>有向图</strong>。无向图由<strong>顶点</strong>和<strong>边</strong>构成，有向图由顶点和<strong>弧</strong>构成。弧有<strong>弧尾</strong>和<strong>弧头</strong>之分。</li>
<li>图按照边或弧的多少分为<strong>稀疏图</strong>和<strong>稠密图</strong>。如果任意两个顶点之间都存在边叫<strong>完全图</strong>，有向图的叫<strong>有向完全图</strong>。若无重复的边或顶点到自身的边叫<strong>简单图</strong>。</li>
<li>图中顶点之间有<strong>邻接点、依附</strong>的概念。无向图顶点的边数叫做<strong>度</strong>，有向图顶点分为<strong>入度</strong>和<strong>出度</strong>。</li>
<li>若图上的边或弧带<strong>权</strong>，则称为<strong>网</strong>。</li>
<li>图中顶点间存在<strong>路径</strong>，两顶点存在路径则说明是<strong>连通</strong>的，如果路径最终回到起始点则称为<strong>环</strong>，当中不重复叫<strong>简单路径</strong>。若任意两顶点都是连通的，则图就是<strong>连通图</strong>，有向则是<strong>强连通图</strong>。图中有子图，若子图极大连通则就是<strong>连通分量</strong>，有向图则称为<strong>强连通分量</strong>。</li>
<li>无向图中连通且 n 个顶点 n-1 条边叫做<strong>生成树</strong>。有向图中一顶点入度为0，其余顶点入度为1的叫做<strong>有向树</strong>。一个有向图由若干棵有向树构成<strong>生成森林</strong>。</li>
</ol>
<h3 id="二、连通图的最小生成树算法"><a href="#二、连通图的最小生成树算法" class="headerlink" title="二、连通图的最小生成树算法"></a>二、连通图的最小生成树算法</h3><p><img src="/posts/4a73b033/5.png" alt="连通带权无向图"><br>  如上是一个带权值的图，即网结构。所谓的最小成本，就是 n 个顶点，用 n-1 条边把一个连通图连接起来，并使得权值的和最小。</p>
<table>
<thead>
<tr>
<th>方案一</th>
<th>方案二</th>
<th>方案三</th>
</tr>
</thead>
<tbody><tr>
<td><img src="/posts/4a73b033/6.png"></td>
<td><img src="/posts/4a73b033/7.png"></td>
<td><img src="/posts/4a73b033/8.png"></td>
</tr>
<tr>
<td>11+26+20+22+18+21+24+19&#x3D;161</td>
<td>8+12+10+11+17+19+16+7&#x3D;100</td>
<td>8+12+10+11+16+19+7&#x3D;99</td>
</tr>
</tbody></table>
<p>  一个连通图的生成树是一个极小的连通子图，它含有图中全部的顶点，但只有足以构成一颗树的 n-1 条边。以上三个方案都是上图的生成树。<strong>我们将构造连通网的最小代价生成树称为最小生成树</strong>。</p>
<h4 id="1、普里姆算法（Prim）"><a href="#1、普里姆算法（Prim）" class="headerlink" title="1、普里姆算法（Prim）"></a>1、普里姆算法（Prim）</h4><table>
<thead>
<tr>
<th>带权连通图</th>
<th>邻接矩阵</th>
</tr>
</thead>
<tbody><tr>
<td><img src="/posts/4a73b033/5.png"></td>
<td><img src="/posts/4a73b033/9.png"></td>
</tr>
</tbody></table>
<p>  普里姆（Prim）算法的实现过程定义如下：假设 N &#x3D; (P,{E}) 是<strong>连通图</strong>，TE 是 N 上最小生成树中边的集合。算法从 U &#x3D; {u<sub>0</sub>} (u<sub>0</sub>∈V)，TE &#x3D; {} 开始。重复执行以下操作：在所有 u∈U，v∈V-U 的边 (u,v)∈E 中找一条代价最小的边 (u<sub>0</sub>,v<sub>0</sub>)并入集合TE，同时v<sub>0</sub>并入U，直到 U &#x3D; V 为止。此时 TE 中必有 n-1 条边，则 T &#x3D; (V,{TE}) 为 N 的最小生成树。由算法代码中的循环嵌套可得知此算法的时间复杂度为 O(n<sup>2</sup>)</p>
<pre class="language-java" data-language="java"><code class="language-java"><span class="token keyword">class</span> <span class="token class-name">MGrap</span> <span class="token punctuation">&#123;</span>
    <span class="token keyword">final</span> <span class="token keyword">int</span> INFINITY <span class="token operator">=</span> <span class="token number">65535</span><span class="token punctuation">;</span><span class="token comment">//很大很大的数</span>
    <span class="token keyword">int</span> numVertexes <span class="token operator">=</span> <span class="token number">9</span><span class="token punctuation">;</span>
    <span class="token keyword">int</span><span class="token punctuation">[</span><span class="token punctuation">]</span><span class="token punctuation">[</span><span class="token punctuation">]</span> arc <span class="token operator">=</span> <span class="token punctuation">&#123;</span><span class="token punctuation">&#123;</span><span class="token number">0</span><span class="token punctuation">,</span> <span class="token number">10</span><span class="token punctuation">,</span> INFINITY<span class="token punctuation">,</span> INFINITY<span class="token punctuation">,</span> INFINITY<span class="token punctuation">,</span> <span class="token number">11</span><span class="token punctuation">,</span> INFINITY<span class="token punctuation">,</span> INFINITY<span class="token punctuation">,</span> INFINITY<span class="token punctuation">&#125;</span><span class="token punctuation">,</span>
            <span class="token punctuation">&#123;</span><span class="token number">10</span><span class="token punctuation">,</span> <span class="token number">0</span><span class="token punctuation">,</span> <span class="token number">18</span><span class="token punctuation">,</span> INFINITY<span class="token punctuation">,</span> INFINITY<span class="token punctuation">,</span> INFINITY<span class="token punctuation">,</span> <span class="token number">16</span><span class="token punctuation">,</span> INFINITY<span class="token punctuation">,</span> <span class="token number">12</span><span class="token punctuation">&#125;</span><span class="token punctuation">,</span>
            <span class="token punctuation">&#123;</span>INFINITY<span class="token punctuation">,</span> INFINITY<span class="token punctuation">,</span> <span class="token number">0</span><span class="token punctuation">,</span> <span class="token number">22</span><span class="token punctuation">,</span> INFINITY<span class="token punctuation">,</span> INFINITY<span class="token punctuation">,</span> INFINITY<span class="token punctuation">,</span> INFINITY<span class="token punctuation">,</span> <span class="token number">8</span><span class="token punctuation">&#125;</span><span class="token punctuation">,</span>
            <span class="token punctuation">&#123;</span>INFINITY<span class="token punctuation">,</span> INFINITY<span class="token punctuation">,</span> <span class="token number">22</span><span class="token punctuation">,</span> <span class="token number">0</span><span class="token punctuation">,</span> <span class="token number">20</span><span class="token punctuation">,</span> INFINITY<span class="token punctuation">,</span> <span class="token number">24</span><span class="token punctuation">,</span> <span class="token number">16</span><span class="token punctuation">,</span> <span class="token number">21</span><span class="token punctuation">&#125;</span><span class="token punctuation">,</span>
            <span class="token punctuation">&#123;</span>INFINITY<span class="token punctuation">,</span> INFINITY<span class="token punctuation">,</span> INFINITY<span class="token punctuation">,</span> <span class="token number">20</span><span class="token punctuation">,</span> <span class="token number">0</span><span class="token punctuation">,</span> <span class="token number">26</span><span class="token punctuation">,</span> INFINITY<span class="token punctuation">,</span> <span class="token number">7</span><span class="token punctuation">,</span> INFINITY<span class="token punctuation">&#125;</span><span class="token punctuation">,</span>
            <span class="token punctuation">&#123;</span><span class="token number">11</span><span class="token punctuation">,</span> INFINITY<span class="token punctuation">,</span> INFINITY<span class="token punctuation">,</span> INFINITY<span class="token punctuation">,</span> <span class="token number">26</span><span class="token punctuation">,</span> <span class="token number">0</span><span class="token punctuation">,</span> <span class="token number">17</span><span class="token punctuation">,</span> INFINITY<span class="token punctuation">,</span> INFINITY<span class="token punctuation">&#125;</span><span class="token punctuation">,</span>
            <span class="token punctuation">&#123;</span>INFINITY<span class="token punctuation">,</span> <span class="token number">16</span><span class="token punctuation">,</span> INFINITY<span class="token punctuation">,</span> INFINITY<span class="token punctuation">,</span> INFINITY<span class="token punctuation">,</span> <span class="token number">17</span><span class="token punctuation">,</span> <span class="token number">0</span><span class="token punctuation">,</span> <span class="token number">19</span><span class="token punctuation">,</span> INFINITY<span class="token punctuation">&#125;</span><span class="token punctuation">,</span>
            <span class="token punctuation">&#123;</span>INFINITY<span class="token punctuation">,</span> INFINITY<span class="token punctuation">,</span> INFINITY<span class="token punctuation">,</span> <span class="token number">16</span><span class="token punctuation">,</span> <span class="token number">7</span><span class="token punctuation">,</span> INFINITY<span class="token punctuation">,</span> <span class="token number">19</span><span class="token punctuation">,</span> <span class="token number">0</span><span class="token punctuation">,</span> INFINITY<span class="token punctuation">&#125;</span><span class="token punctuation">,</span>
            <span class="token punctuation">&#123;</span>INFINITY<span class="token punctuation">,</span> <span class="token number">12</span><span class="token punctuation">,</span> <span class="token number">8</span><span class="token punctuation">,</span> <span class="token number">21</span><span class="token punctuation">,</span> INFINITY<span class="token punctuation">,</span> INFINITY<span class="token punctuation">,</span> INFINITY<span class="token punctuation">,</span> INFINITY<span class="token punctuation">,</span> <span class="token number">0</span><span class="token punctuation">&#125;</span><span class="token punctuation">&#125;</span><span class="token punctuation">;</span>
<span class="token punctuation">&#125;</span>

<span class="token keyword">public</span> <span class="token keyword">class</span> <span class="token class-name">GrapTest</span> <span class="token punctuation">&#123;</span>
    <span class="token annotation punctuation">@Test</span>
    <span class="token keyword">public</span> <span class="token keyword">void</span> <span class="token function">test</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
        <span class="token class-name">MGrap</span> g <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">MGrap</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token class-name">MiniSpanTree_Prim</span><span class="token punctuation">(</span>g<span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token punctuation">&#125;</span>

    <span class="token keyword">public</span> <span class="token keyword">void</span> <span class="token class-name">MiniSpanTree_Prim</span><span class="token punctuation">(</span><span class="token class-name">MGrap</span> <span class="token class-name">G</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
        <span class="token keyword">int</span> min<span class="token punctuation">,</span> i<span class="token punctuation">,</span> j<span class="token punctuation">,</span> k<span class="token punctuation">;</span>
        <span class="token keyword">int</span><span class="token punctuation">[</span><span class="token punctuation">]</span> adjvex <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token keyword">int</span><span class="token punctuation">[</span><span class="token class-name">G</span><span class="token punctuation">.</span>numVertexes<span class="token punctuation">]</span><span class="token punctuation">;</span>
        <span class="token keyword">int</span><span class="token punctuation">[</span><span class="token punctuation">]</span> lowcost <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token keyword">int</span><span class="token punctuation">[</span><span class="token class-name">G</span><span class="token punctuation">.</span>numVertexes<span class="token punctuation">]</span><span class="token punctuation">;</span>
        lowcost<span class="token punctuation">[</span><span class="token number">0</span><span class="token punctuation">]</span> <span class="token operator">=</span> <span class="token number">0</span><span class="token punctuation">;</span><span class="token comment">//相当于先将 V0 加入生成树</span>
        adjvex<span class="token punctuation">[</span><span class="token number">0</span><span class="token punctuation">]</span> <span class="token operator">=</span> <span class="token number">0</span><span class="token punctuation">;</span>

        <span class="token comment">//lowcost[i]永远代表的是边adjvex[i]-->i的代价</span>
        <span class="token keyword">for</span> <span class="token punctuation">(</span>i <span class="token operator">=</span> <span class="token number">1</span><span class="token punctuation">;</span> i <span class="token operator">&lt;</span> <span class="token class-name">G</span><span class="token punctuation">.</span>numVertexes<span class="token punctuation">;</span> i<span class="token operator">++</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
            lowcost<span class="token punctuation">[</span>i<span class="token punctuation">]</span> <span class="token operator">=</span> <span class="token class-name">G</span><span class="token punctuation">.</span>arc<span class="token punctuation">[</span><span class="token number">0</span><span class="token punctuation">]</span><span class="token punctuation">[</span>i<span class="token punctuation">]</span><span class="token punctuation">;</span><span class="token comment">// V0到其他各顶点的代价，因为目前生成树中只有V0</span>
            adjvex<span class="token punctuation">[</span>i<span class="token punctuation">]</span> <span class="token operator">=</span> <span class="token number">0</span><span class="token punctuation">;</span>
        <span class="token punctuation">&#125;</span>

        <span class="token keyword">for</span> <span class="token punctuation">(</span>i <span class="token operator">=</span> <span class="token number">1</span><span class="token punctuation">;</span> i <span class="token operator">&lt;</span> <span class="token class-name">G</span><span class="token punctuation">.</span>numVertexes<span class="token punctuation">;</span> i<span class="token operator">++</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
            min <span class="token operator">=</span> <span class="token class-name">G</span><span class="token punctuation">.</span>INFINITY<span class="token punctuation">;</span>
            j <span class="token operator">=</span> <span class="token number">1</span><span class="token punctuation">;</span> k <span class="token operator">=</span> <span class="token number">0</span><span class="token punctuation">;</span>
            <span class="token keyword">while</span> <span class="token punctuation">(</span>j <span class="token operator">&lt;</span> <span class="token class-name">G</span><span class="token punctuation">.</span>numVertexes<span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
            	<span class="token comment">//已经加入到最小生成树中的顶点，其对应的lowcost值为0</span>
                <span class="token keyword">if</span> <span class="token punctuation">(</span>lowcost<span class="token punctuation">[</span>j<span class="token punctuation">]</span> <span class="token operator">!=</span> <span class="token number">0</span> <span class="token operator">&amp;&amp;</span> lowcost<span class="token punctuation">[</span>j<span class="token punctuation">]</span> <span class="token operator">&lt;</span> min<span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
                    min <span class="token operator">=</span> lowcost<span class="token punctuation">[</span>j<span class="token punctuation">]</span><span class="token punctuation">;</span>
                    k <span class="token operator">=</span> j<span class="token punctuation">;</span>
                <span class="token punctuation">&#125;</span>
                j<span class="token operator">++</span><span class="token punctuation">;</span>
            <span class="token punctuation">&#125;</span>

            lowcost<span class="token punctuation">[</span>k<span class="token punctuation">]</span> <span class="token operator">=</span> <span class="token number">0</span><span class="token punctuation">;</span> <span class="token comment">//将 Vk 加入生成树</span>
            <span class="token class-name">System</span><span class="token punctuation">.</span>out<span class="token punctuation">.</span><span class="token function">println</span><span class="token punctuation">(</span>adjvex<span class="token punctuation">[</span>k<span class="token punctuation">]</span> <span class="token operator">+</span> <span class="token string">" --> "</span> <span class="token operator">+</span> k<span class="token punctuation">)</span><span class="token punctuation">;</span><span class="token comment">//打印拥有最小权值的边</span>
			<span class="token comment">//新的顶点加入到生成树集合后，lowcost和adjvex数组会有相应的变化</span>
            <span class="token keyword">for</span> <span class="token punctuation">(</span>j <span class="token operator">=</span> <span class="token number">1</span><span class="token punctuation">;</span> j <span class="token operator">&lt;</span> <span class="token class-name">G</span><span class="token punctuation">.</span>numVertexes<span class="token punctuation">;</span> j<span class="token operator">++</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
                <span class="token keyword">if</span> <span class="token punctuation">(</span>lowcost<span class="token punctuation">[</span>j<span class="token punctuation">]</span> <span class="token operator">!=</span> <span class="token number">0</span> <span class="token operator">&amp;&amp;</span> <span class="token class-name">G</span><span class="token punctuation">.</span>arc<span class="token punctuation">[</span>k<span class="token punctuation">]</span><span class="token punctuation">[</span>j<span class="token punctuation">]</span> <span class="token operator">&lt;</span> lowcost<span class="token punctuation">[</span>j<span class="token punctuation">]</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
                    lowcost<span class="token punctuation">[</span>j<span class="token punctuation">]</span> <span class="token operator">=</span> <span class="token class-name">G</span><span class="token punctuation">.</span>arc<span class="token punctuation">[</span>k<span class="token punctuation">]</span><span class="token punctuation">[</span>j<span class="token punctuation">]</span><span class="token punctuation">;</span>
                    adjvex<span class="token punctuation">[</span>j<span class="token punctuation">]</span> <span class="token operator">=</span> k<span class="token punctuation">;</span>
                <span class="token punctuation">&#125;</span>
            <span class="token punctuation">&#125;</span>
        <span class="token punctuation">&#125;</span>
    <span class="token punctuation">&#125;</span>
<span class="token punctuation">&#125;</span></code></pre>

<h4 id="2、克鲁斯卡尔算法（Kruskal）"><a href="#2、克鲁斯卡尔算法（Kruskal）" class="headerlink" title="2、克鲁斯卡尔算法（Kruskal）"></a>2、克鲁斯卡尔算法（Kruskal）</h4><p>  普里姆（Prim）算法是以某顶点为起点，逐步找各顶点上最小权值的边来构建最小生成树。其实，我们也可以直接以边为目标区构建，因为权值是在边上，直接去找最小权值的边来构建生成树也是很自然的想法，但是构建时要考虑是否会形成环路。此时要用到图的存储结构中的边集数据结构。<br>  克鲁斯卡尔（Kruskal）算法的实现过程定义如下：假设 N &#x3D; (V,{E}) 是连通网，则令最小生成树的初始状态为只有 n 个顶点而无边的非连通图 T &#x3D; {V,{}}，图中每个顶点自成一个连通分量。在 E 中选择代价最小的边，若该边依附的顶点落在 T 中不同的连通分量上，则将此边加入到 T 中，否则舍弃此边而选择下一条代价最小的边。依次类推，直至 T 中所有顶点都在同一连通分量上为止。此算法的find函数由边数 e 决定，时间复杂度为 O(log(e))，而外层有一个 for 循环 e 次。所以克鲁斯卡尔算法的<strong>时间复杂度为 O(e*log(e))</strong></p>
<pre class="language-java" data-language="java"><code class="language-java"><span class="token keyword">class</span> <span class="token class-name">Edge</span> <span class="token punctuation">&#123;</span>
    <span class="token keyword">int</span> begin<span class="token punctuation">;</span>
    <span class="token keyword">int</span> end<span class="token punctuation">;</span>
    <span class="token keyword">int</span> weight<span class="token punctuation">;</span>

    <span class="token keyword">public</span> <span class="token class-name">Edge</span><span class="token punctuation">(</span><span class="token keyword">int</span> begin<span class="token punctuation">,</span> <span class="token keyword">int</span> end<span class="token punctuation">,</span> <span class="token keyword">int</span> weight<span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
        <span class="token keyword">this</span><span class="token punctuation">.</span>begin <span class="token operator">=</span> begin<span class="token punctuation">;</span>
        <span class="token keyword">this</span><span class="token punctuation">.</span>end <span class="token operator">=</span> end<span class="token punctuation">;</span>
        <span class="token keyword">this</span><span class="token punctuation">.</span>weight <span class="token operator">=</span> weight<span class="token punctuation">;</span>
    <span class="token punctuation">&#125;</span>

    <span class="token keyword">public</span> <span class="token class-name">String</span> <span class="token function">toString</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
        <span class="token keyword">return</span> begin <span class="token operator">+</span> <span class="token string">"---"</span> <span class="token operator">+</span> end <span class="token operator">+</span> <span class="token string">": "</span> <span class="token operator">+</span> weight<span class="token punctuation">;</span>
    <span class="token punctuation">&#125;</span>
<span class="token punctuation">&#125;</span>

<span class="token keyword">class</span> <span class="token class-name">MGrap</span> <span class="token punctuation">&#123;</span>
    <span class="token keyword">final</span> <span class="token keyword">int</span> INFINITY <span class="token operator">=</span> <span class="token number">65535</span><span class="token punctuation">;</span><span class="token comment">//很大很大的数</span>
    <span class="token keyword">int</span> numVertexes <span class="token operator">=</span> <span class="token number">9</span><span class="token punctuation">;</span>
    <span class="token keyword">int</span> numEdges <span class="token operator">=</span> <span class="token number">15</span><span class="token punctuation">;</span>
    <span class="token keyword">int</span><span class="token punctuation">[</span><span class="token punctuation">]</span><span class="token punctuation">[</span><span class="token punctuation">]</span> arc <span class="token operator">=</span> <span class="token punctuation">&#123;</span><span class="token punctuation">&#123;</span><span class="token number">0</span><span class="token punctuation">,</span> <span class="token number">10</span><span class="token punctuation">,</span> INFINITY<span class="token punctuation">,</span> INFINITY<span class="token punctuation">,</span> INFINITY<span class="token punctuation">,</span> <span class="token number">11</span><span class="token punctuation">,</span> INFINITY<span class="token punctuation">,</span> INFINITY<span class="token punctuation">,</span> INFINITY<span class="token punctuation">&#125;</span><span class="token punctuation">,</span>
            <span class="token punctuation">&#123;</span><span class="token number">10</span><span class="token punctuation">,</span> <span class="token number">0</span><span class="token punctuation">,</span> <span class="token number">18</span><span class="token punctuation">,</span> INFINITY<span class="token punctuation">,</span> INFINITY<span class="token punctuation">,</span> INFINITY<span class="token punctuation">,</span> <span class="token number">16</span><span class="token punctuation">,</span> INFINITY<span class="token punctuation">,</span> <span class="token number">12</span><span class="token punctuation">&#125;</span><span class="token punctuation">,</span>
            <span class="token punctuation">&#123;</span>INFINITY<span class="token punctuation">,</span> INFINITY<span class="token punctuation">,</span> <span class="token number">0</span><span class="token punctuation">,</span> <span class="token number">22</span><span class="token punctuation">,</span> INFINITY<span class="token punctuation">,</span> INFINITY<span class="token punctuation">,</span> INFINITY<span class="token punctuation">,</span> INFINITY<span class="token punctuation">,</span> <span class="token number">8</span><span class="token punctuation">&#125;</span><span class="token punctuation">,</span>
            <span class="token punctuation">&#123;</span>INFINITY<span class="token punctuation">,</span> INFINITY<span class="token punctuation">,</span> <span class="token number">22</span><span class="token punctuation">,</span> <span class="token number">0</span><span class="token punctuation">,</span> <span class="token number">20</span><span class="token punctuation">,</span> INFINITY<span class="token punctuation">,</span> <span class="token number">24</span><span class="token punctuation">,</span> <span class="token number">16</span><span class="token punctuation">,</span> <span class="token number">21</span><span class="token punctuation">&#125;</span><span class="token punctuation">,</span>
            <span class="token punctuation">&#123;</span>INFINITY<span class="token punctuation">,</span> INFINITY<span class="token punctuation">,</span> INFINITY<span class="token punctuation">,</span> <span class="token number">20</span><span class="token punctuation">,</span> <span class="token number">0</span><span class="token punctuation">,</span> <span class="token number">26</span><span class="token punctuation">,</span> INFINITY<span class="token punctuation">,</span> <span class="token number">7</span><span class="token punctuation">,</span> INFINITY<span class="token punctuation">&#125;</span><span class="token punctuation">,</span>
            <span class="token punctuation">&#123;</span><span class="token number">11</span><span class="token punctuation">,</span> INFINITY<span class="token punctuation">,</span> INFINITY<span class="token punctuation">,</span> INFINITY<span class="token punctuation">,</span> <span class="token number">26</span><span class="token punctuation">,</span> <span class="token number">0</span><span class="token punctuation">,</span> <span class="token number">17</span><span class="token punctuation">,</span> INFINITY<span class="token punctuation">,</span> INFINITY<span class="token punctuation">&#125;</span><span class="token punctuation">,</span>
            <span class="token punctuation">&#123;</span>INFINITY<span class="token punctuation">,</span> <span class="token number">16</span><span class="token punctuation">,</span> INFINITY<span class="token punctuation">,</span> INFINITY<span class="token punctuation">,</span> INFINITY<span class="token punctuation">,</span> <span class="token number">17</span><span class="token punctuation">,</span> <span class="token number">0</span><span class="token punctuation">,</span> <span class="token number">19</span><span class="token punctuation">,</span> INFINITY<span class="token punctuation">&#125;</span><span class="token punctuation">,</span>
            <span class="token punctuation">&#123;</span>INFINITY<span class="token punctuation">,</span> INFINITY<span class="token punctuation">,</span> INFINITY<span class="token punctuation">,</span> <span class="token number">16</span><span class="token punctuation">,</span> <span class="token number">7</span><span class="token punctuation">,</span> INFINITY<span class="token punctuation">,</span> <span class="token number">19</span><span class="token punctuation">,</span> <span class="token number">0</span><span class="token punctuation">,</span> INFINITY<span class="token punctuation">&#125;</span><span class="token punctuation">,</span>
            <span class="token punctuation">&#123;</span>INFINITY<span class="token punctuation">,</span> <span class="token number">12</span><span class="token punctuation">,</span> <span class="token number">8</span><span class="token punctuation">,</span> <span class="token number">21</span><span class="token punctuation">,</span> INFINITY<span class="token punctuation">,</span> INFINITY<span class="token punctuation">,</span> INFINITY<span class="token punctuation">,</span> INFINITY<span class="token punctuation">,</span> <span class="token number">0</span><span class="token punctuation">&#125;</span><span class="token punctuation">&#125;</span><span class="token punctuation">;</span>
<span class="token punctuation">&#125;</span>

<span class="token keyword">public</span> <span class="token keyword">class</span> <span class="token class-name">GrapTest</span> <span class="token punctuation">&#123;</span>
    <span class="token annotation punctuation">@Test</span>
    <span class="token keyword">public</span> <span class="token keyword">void</span> <span class="token function">test</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
        <span class="token class-name">MGrap</span> g <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">MGrap</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token class-name">MiniSpanTree_Kruskal</span><span class="token punctuation">(</span>g<span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token punctuation">&#125;</span>

    <span class="token keyword">public</span> <span class="token keyword">void</span> <span class="token class-name">MiniSpanTree_Kruskal</span><span class="token punctuation">(</span><span class="token class-name">MGrap</span> <span class="token class-name">G</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
        <span class="token keyword">int</span> i<span class="token punctuation">,</span> n<span class="token punctuation">,</span> m<span class="token punctuation">;</span>
        <span class="token class-name">Edge</span><span class="token punctuation">[</span><span class="token punctuation">]</span> edges <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">Edge</span><span class="token punctuation">[</span><span class="token class-name">G</span><span class="token punctuation">.</span>numEdges<span class="token punctuation">]</span><span class="token punctuation">;</span><span class="token comment">//边集数组</span>
        <span class="token keyword">int</span><span class="token punctuation">[</span><span class="token punctuation">]</span> parent <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token keyword">int</span><span class="token punctuation">[</span><span class="token class-name">G</span><span class="token punctuation">.</span>numVertexes<span class="token punctuation">]</span><span class="token punctuation">;</span>

        <span class="token comment">/*将图的邻接矩阵转换成边集数组edges，并按权值由小到大排序*/</span>
        <span class="token keyword">int</span> j<span class="token punctuation">,</span> k<span class="token punctuation">;</span>
        <span class="token keyword">for</span> <span class="token punctuation">(</span>i <span class="token operator">=</span> <span class="token number">0</span><span class="token punctuation">,</span> k <span class="token operator">=</span> <span class="token number">0</span><span class="token punctuation">;</span> i <span class="token operator">&lt;</span> <span class="token class-name">G</span><span class="token punctuation">.</span>numVertexes<span class="token punctuation">;</span> i<span class="token operator">++</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
            <span class="token keyword">for</span> <span class="token punctuation">(</span>j <span class="token operator">=</span> i <span class="token operator">+</span> <span class="token number">1</span><span class="token punctuation">;</span> j <span class="token operator">&lt;</span> <span class="token class-name">G</span><span class="token punctuation">.</span>numVertexes<span class="token punctuation">;</span> j<span class="token operator">++</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
                <span class="token keyword">if</span> <span class="token punctuation">(</span><span class="token class-name">G</span><span class="token punctuation">.</span>arc<span class="token punctuation">[</span>i<span class="token punctuation">]</span><span class="token punctuation">[</span>j<span class="token punctuation">]</span> <span class="token operator">&lt;</span> <span class="token class-name">G</span><span class="token punctuation">.</span>INFINITY<span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
                    edges<span class="token punctuation">[</span>k<span class="token operator">++</span><span class="token punctuation">]</span> <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">Edge</span><span class="token punctuation">(</span>i<span class="token punctuation">,</span> j<span class="token punctuation">,</span> <span class="token class-name">G</span><span class="token punctuation">.</span>arc<span class="token punctuation">[</span>i<span class="token punctuation">]</span><span class="token punctuation">[</span>j<span class="token punctuation">]</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
                <span class="token punctuation">&#125;</span>
            <span class="token punctuation">&#125;</span>
        <span class="token punctuation">&#125;</span>
        <span class="token class-name">Arrays</span><span class="token punctuation">.</span><span class="token function">sort</span><span class="token punctuation">(</span>edges<span class="token punctuation">,</span> <span class="token punctuation">(</span>e1<span class="token punctuation">,</span> e2<span class="token punctuation">)</span> <span class="token operator">-></span> e1<span class="token punctuation">.</span>weight <span class="token operator">-</span> e2<span class="token punctuation">.</span>weight<span class="token punctuation">)</span><span class="token punctuation">;</span><span class="token comment">//Lambda表达式</span>
        <span class="token comment">//Arrays.stream(edges).forEach(System.out::println);//方法引用</span>

        <span class="token keyword">for</span> <span class="token punctuation">(</span>i <span class="token operator">=</span> <span class="token number">0</span><span class="token punctuation">;</span> i <span class="token operator">&lt;</span> <span class="token class-name">G</span><span class="token punctuation">.</span>numVertexes<span class="token punctuation">;</span> i<span class="token operator">++</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
            parent<span class="token punctuation">[</span>i<span class="token punctuation">]</span> <span class="token operator">=</span> <span class="token number">0</span><span class="token punctuation">;</span>
        <span class="token punctuation">&#125;</span>

        <span class="token keyword">for</span> <span class="token punctuation">(</span>i <span class="token operator">=</span> <span class="token number">0</span><span class="token punctuation">;</span> i <span class="token operator">&lt;</span> <span class="token class-name">G</span><span class="token punctuation">.</span>numEdges<span class="token punctuation">;</span> i<span class="token operator">++</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span><span class="token comment">//循环每条边</span>
        	<span class="token comment">//若begin和end在不同的连通分量上，则find函数返回的值不相等。</span>
            <span class="token comment">//相反，若begin和end在同一个连通分量上，则find函数返回的值相等。</span>
            n <span class="token operator">=</span> <span class="token function">find</span><span class="token punctuation">(</span>parent<span class="token punctuation">,</span> edges<span class="token punctuation">[</span>i<span class="token punctuation">]</span><span class="token punctuation">.</span>begin<span class="token punctuation">)</span><span class="token punctuation">;</span>
            m <span class="token operator">=</span> <span class="token function">find</span><span class="token punctuation">(</span>parent<span class="token punctuation">,</span> edges<span class="token punctuation">[</span>i<span class="token punctuation">]</span><span class="token punctuation">.</span>end<span class="token punctuation">)</span><span class="token punctuation">;</span>
            <span class="token keyword">if</span> <span class="token punctuation">(</span>n <span class="token operator">!=</span> m<span class="token punctuation">)</span> <span class="token punctuation">&#123;</span><span class="token comment">//此边没有与现生成树形成环</span>
                parent<span class="token punctuation">[</span>n<span class="token punctuation">]</span> <span class="token operator">=</span> m<span class="token punctuation">;</span>
                <span class="token comment">//打印拥有最小权值的边</span>
                <span class="token class-name">System</span><span class="token punctuation">.</span>out<span class="token punctuation">.</span><span class="token function">println</span><span class="token punctuation">(</span>edges<span class="token punctuation">[</span>i<span class="token punctuation">]</span><span class="token punctuation">.</span>begin <span class="token operator">+</span> <span class="token string">" --> "</span> <span class="token operator">+</span> edges<span class="token punctuation">[</span>i<span class="token punctuation">]</span><span class="token punctuation">.</span>end<span class="token punctuation">)</span><span class="token punctuation">;</span>
            <span class="token punctuation">&#125;</span>
        <span class="token punctuation">&#125;</span>
    <span class="token punctuation">&#125;</span>

    <span class="token comment">//在构建生成树的过程中，所有顶点和已经加入的边会形成多个连通分量。</span>
    <span class="token comment">//在同一个连通分量上，任意两个顶点按照以下方法，总会返回相同顶点（注意体会）</span>
    <span class="token keyword">int</span> <span class="token function">find</span><span class="token punctuation">(</span><span class="token keyword">int</span><span class="token punctuation">[</span><span class="token punctuation">]</span> parent<span class="token punctuation">,</span> <span class="token keyword">int</span> f<span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
        <span class="token keyword">while</span> <span class="token punctuation">(</span>parent<span class="token punctuation">[</span>f<span class="token punctuation">]</span> <span class="token operator">></span> <span class="token number">0</span><span class="token punctuation">)</span>
            f <span class="token operator">=</span> parent<span class="token punctuation">[</span>f<span class="token punctuation">]</span><span class="token punctuation">;</span>
        <span class="token keyword">return</span> f<span class="token punctuation">;</span>
    <span class="token punctuation">&#125;</span>
<span class="token punctuation">&#125;</span></code></pre>

<h4 id="3、对比分析"><a href="#3、对比分析" class="headerlink" title="3、对比分析"></a>3、对比分析</h4><p>  对比普里姆（Prim）算法和克鲁斯卡尔（Kruskal）算法可知，kruskal算法主要是针对边来展开，当图中的边数少是效率会非常高，所以对于稀疏图有很大的优势；而Prim算法主要是针对顶点来展开，对于稠密图或者边数非常多的情况效率会好一些。</p>

                
            </div>
            <hr/>

            

    <div class="reprint" id="reprint-statement">
        
            <div class="reprint__author">
                <span class="reprint-meta" style="font-weight: bold;">
                    <i class="fas fa-user">
                        文章作者:
                    </i>
                </span>
                <span class="reprint-info">
                    <a href="/about" rel="external nofollow noreferrer">YangChongZhi</a>
                </span>
            </div>
            <div class="reprint__type">
                <span class="reprint-meta" style="font-weight: bold;">
                    <i class="fas fa-link">
                        文章链接:
                    </i>
                </span>
                <span class="reprint-info">
                    <a href="http://yczlab.top/posts/4a73b033.html">http://yczlab.top/posts/4a73b033.html</a>
                </span>
            </div>
            <div class="reprint__notice">
                <span class="reprint-meta" style="font-weight: bold;">
                    <i class="fas fa-copyright">
                        版权声明:
                    </i>
                </span>
                <span class="reprint-info">
                    本博客所有文章除特別声明外，均采用
                    <a href="https://creativecommons.org/licenses/by/4.0/deed.zh" rel="external nofollow noreferrer" target="_blank">CC BY 4.0</a>
                    许可协议。转载请注明来源
                    <a href="/about" target="_blank">YangChongZhi</a>
                    !
                </span>
            </div>
        
    </div>

    <script async defer>
      document.addEventListener("copy", function (e) {
        let toastHTML = '<span>复制成功，请遵循本文的转载规则</span><button class="btn-flat toast-action" onclick="navToReprintStatement()" style="font-size: smaller">查看</a>';
        M.toast({html: toastHTML})
      });

      function navToReprintStatement() {
        $("html, body").animate({scrollTop: $("#reprint-statement").offset().top - 80}, 800);
      }
    </script>



            <div class="tag_share" style="display: block;">
                <div class="post-meta__tag-list" style="display: inline-block;">
                    
                        <div class="article-tag">
                            
                                <a href="/tags/Java/">
                                    <span class="chip bg-color">Java</span>
                                </a>
                            
                                <a href="/tags/Algorithm/">
                                    <span class="chip bg-color">Algorithm</span>
                                </a>
                            
                                <a href="/tags/DataStructure/">
                                    <span class="chip bg-color">DataStructure</span>
                                </a>
                            
                        </div>
                    
                </div>
                <div class="post_share" style="zoom: 80%; width: fit-content; display: inline-block; float: right; margin: -0.15rem 0;">
                    <link rel="stylesheet" type="text/css" href="/libs/share/css/share.min.css">
<div id="article-share">

    
    <div class="social-share" data-sites="twitter,facebook,google,qq,qzone,wechat,weibo,douban,linkedin" data-wechat-qrcode-helper="<p>微信扫一扫即可分享！</p>"></div>
    <script src="/libs/share/js/social-share.min.js"></script>
    

    

</div>

                </div>
            </div>
            
                <style>
    #reward {
        margin: 40px 0;
        text-align: center;
    }

    #reward .reward-link {
        font-size: 1.4rem;
        line-height: 38px;
    }

    #reward .btn-floating:hover {
        box-shadow: 0 6px 12px rgba(0, 0, 0, 0.2), 0 5px 15px rgba(0, 0, 0, 0.2);
    }

    #rewardModal {
        width: 320px;
        height: 350px;
    }

    #rewardModal .reward-title {
        margin: 15px auto;
        padding-bottom: 5px;
    }

    #rewardModal .modal-content {
        padding: 10px;
    }

    #rewardModal .close {
        position: absolute;
        right: 15px;
        top: 15px;
        color: rgba(0, 0, 0, 0.5);
        font-size: 1.3rem;
        line-height: 20px;
        cursor: pointer;
    }

    #rewardModal .close:hover {
        color: #ef5350;
        transform: scale(1.3);
        -moz-transform:scale(1.3);
        -webkit-transform:scale(1.3);
        -o-transform:scale(1.3);
    }

    #rewardModal .reward-tabs {
        margin: 0 auto;
        width: 210px;
    }

    .reward-tabs .tabs {
        height: 38px;
        margin: 10px auto;
        padding-left: 0;
    }

    .reward-content ul {
        padding-left: 0 !important;
    }

    .reward-tabs .tabs .tab {
        height: 38px;
        line-height: 38px;
    }

    .reward-tabs .tab a {
        color: #fff;
        background-color: #ccc;
    }

    .reward-tabs .tab a:hover {
        background-color: #ccc;
        color: #fff;
    }

    .reward-tabs .wechat-tab .active {
        color: #fff !important;
        background-color: #22AB38 !important;
    }

    .reward-tabs .alipay-tab .active {
        color: #fff !important;
        background-color: #019FE8 !important;
    }

    .reward-tabs .reward-img {
        width: 210px;
        height: 210px;
    }
</style>

<div id="reward">
    <a href="#rewardModal" class="reward-link modal-trigger btn-floating btn-medium waves-effect waves-light red">赏</a>

    <!-- Modal Structure -->
    <div id="rewardModal" class="modal">
        <div class="modal-content">
            <a class="close modal-close"><i class="fas fa-times"></i></a>
            <h4 class="reward-title">你的赏识是我前进的动力</h4>
            <div class="reward-content">
                <div class="reward-tabs">
                    <ul class="tabs row">
                        <li class="tab col s6 alipay-tab waves-effect waves-light"><a href="#alipay">支付宝</a></li>
                        <li class="tab col s6 wechat-tab waves-effect waves-light"><a href="#wechat">微 信</a></li>
                    </ul>
                    <div id="alipay">
                        <img src="/medias/reward/alipay.jpg" class="reward-img" alt="支付宝打赏二维码">
                    </div>
                    <div id="wechat">
                        <img src="/medias/reward/wechat.png" class="reward-img" alt="微信打赏二维码">
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<script>
    $(function () {
        $('.tabs').tabs();
    });
</script>

            
        </div>
    </div>

    

    

    

    

    
        <style>
    .valine-card {
        margin: 1.5rem auto;
    }

    .valine-card .card-content {
        padding: 20px 20px 5px 20px;
    }

    #vcomments textarea {
        box-sizing: border-box;
        background: url("/medias/comment_bg.webp") 100% 100% no-repeat;
    }

    #vcomments p {
        margin: 2px 2px 10px;
        font-size: 1.05rem;
        line-height: 1.78rem;
    }

    #vcomments blockquote p {
        text-indent: 0.2rem;
    }

    #vcomments a {
        padding: 0 2px;
        color: #4cbf30;
        font-weight: 500;
        text-decoration: none;
    }

    #vcomments img {
        max-width: 100%;
        height: auto;
        cursor: pointer;
    }

    #vcomments ol li {
        list-style-type: decimal;
    }

    #vcomments ol,
    ul {
        display: block;
        padding-left: 2em;
        word-spacing: 0.05rem;
    }

    #vcomments ul li,
    ol li {
        display: list-item;
        line-height: 1.8rem;
        font-size: 1rem;
    }

    #vcomments ul li {
        list-style-type: disc;
    }

    #vcomments ul ul li {
        list-style-type: circle;
    }

    #vcomments table, th, td {
        padding: 12px 13px;
        border: 1px solid #dfe2e5;
    }

    #vcomments table, th, td {
        border: 0;
    }

    table tr:nth-child(2n), thead {
        background-color: #fafafa;
    }

    #vcomments table th {
        background-color: #f2f2f2;
        min-width: 80px;
    }

    #vcomments table td {
        min-width: 80px;
    }

    #vcomments h1 {
        font-size: 1.85rem;
        font-weight: bold;
        line-height: 2.2rem;
    }

    #vcomments h2 {
        font-size: 1.65rem;
        font-weight: bold;
        line-height: 1.9rem;
    }

    #vcomments h3 {
        font-size: 1.45rem;
        font-weight: bold;
        line-height: 1.7rem;
    }

    #vcomments h4 {
        font-size: 1.25rem;
        font-weight: bold;
        line-height: 1.5rem;
    }

    #vcomments h5 {
        font-size: 1.1rem;
        font-weight: bold;
        line-height: 1.4rem;
    }

    #vcomments h6 {
        font-size: 1rem;
        line-height: 1.3rem;
    }

    #vcomments p {
        font-size: 1rem;
        line-height: 1.5rem;
    }

    #vcomments hr {
        margin: 12px 0;
        border: 0;
        border-top: 1px solid #ccc;
    }

    #vcomments blockquote {
        margin: 15px 0;
        border-left: 5px solid #42b983;
        padding: 1rem 0.8rem 0.3rem 0.8rem;
        color: #666;
        background-color: rgba(66, 185, 131, .1);
    }

    #vcomments pre {
        font-family: monospace, monospace;
        padding: 1.2em;
        margin: .5em 0;
        background: #272822;
        overflow: auto;
        border-radius: 0.3em;
        tab-size: 4;
    }

    #vcomments code {
        font-family: monospace, monospace;
        padding: 1px 3px;
        font-size: 0.92rem;
        color: #e96900;
        background-color: #f8f8f8;
        border-radius: 2px;
    }

    #vcomments pre code {
        font-family: monospace, monospace;
        padding: 0;
        color: #e8eaf6;
        background-color: #272822;
    }

    #vcomments pre[class*="language-"] {
        padding: 1.2em;
        margin: .5em 0;
    }

    #vcomments code[class*="language-"],
    pre[class*="language-"] {
        color: #e8eaf6;
    }

    #vcomments [type="checkbox"]:not(:checked), [type="checkbox"]:checked {
        position: inherit;
        margin-left: -1.3rem;
        margin-right: 0.4rem;
        margin-top: -1px;
        vertical-align: middle;
        left: unset;
        visibility: visible;
    }

    #vcomments b,
    strong {
        font-weight: bold;
    }

    #vcomments dfn {
        font-style: italic;
    }

    #vcomments small {
        font-size: 85%;
    }

    #vcomments cite {
        font-style: normal;
    }

    #vcomments mark {
        background-color: #fcf8e3;
        padding: .2em;
    }

    #vcomments table, th, td {
        padding: 12px 13px;
        border: 1px solid #dfe2e5;
    }

    table tr:nth-child(2n), thead {
        background-color: #fafafa;
    }

    #vcomments table th {
        background-color: #f2f2f2;
        min-width: 80px;
    }

    #vcomments table td {
        min-width: 80px;
    }

    #vcomments [type="checkbox"]:not(:checked), [type="checkbox"]:checked {
        position: inherit;
        margin-left: -1.3rem;
        margin-right: 0.4rem;
        margin-top: -1px;
        vertical-align: middle;
        left: unset;
        visibility: visible;
    }
</style>

<div class="card valine-card" data-aos="fade-up">
    <div class="comment_headling" style="font-size: 20px; font-weight: 700; position: relative; padding-left: 20px; top: 15px; padding-bottom: 5px;">
        <i class="fas fa-comments fa-fw" aria-hidden="true"></i>
        <span>评论</span>
    </div>
    <div id="vcomments" class="card-content" style="display: grid">
    </div>
</div>

<script src="/libs/valine/av-min.js"></script>
<script src="/libs/valine/Valine.min.js"></script>
<script>
    new Valine({
        el: '#vcomments',
        appId: 'jJDtz1MXtl9cRxLcrXYvlvhd-9Nh9j0Va',
        appKey: 'UpF6BuVYYhInv6M8vXS0dWRt',
        pageSize: '10',
        notify: 'false' === 'true',
        verify: 'false' === 'true',
        visitor: 'false' === 'true',
        avatar: 'monsterid',
		recordIP: 'true',
		enableQQ: 'true',
		requiredFields: ["nick", "mail"],
        lang: 'zh-cn',
        placeholder: '请开始你的表演吧！\n注意博客留言要求填写昵称、邮箱'
    });
</script>

    

    

    

    

<article id="prenext-posts" class="prev-next articles">
    <div class="row article-row">
        
        <div class="article col s12 m6" data-aos="fade-up">
            <div class="article-badge left-badge text-color">
                <i class="fas fa-chevron-left"></i>&nbsp;上一篇</div>
            <div class="card">
                <a href="/posts/6a16f47a.html">
                    <div class="card-image">
                        
                        
                        <img src="/medias/featureimages/2.jpg" class="responsive-img" alt="图的最短路径算法">
                        
                        <span class="card-title">图的最短路径算法</span>
                    </div>
                </a>
                <div class="card-content article-content">
                    <div class="summary block-with-text">
                        
                              
引言：
图的最短路径问题是求图中两顶点间的最短路径问题。

  在网图和非网图中，最短路径的含义不同。由于非网图它没有边上的权值，所谓的最短路径，其实就是指两顶点之间经过的边数最少的路径；而对于网图来说，最短路径是指两顶点之间经过的边
                        
                    </div>
                    <div class="publish-info">
                        <span class="publish-date">
                            <i class="far fa-clock fa-fw icon-date"></i>2021-01-22
                        </span>
                        <span class="publish-author">
                            
                            <i class="fas fa-bookmark fa-fw icon-category"></i>
                            
                            <a href="/categories/Algorithm/" class="post-category">
                                    Algorithm
                                </a>
                            
                            
                        </span>
                    </div>
                </div>
                
                <div class="card-action article-tags">
                    
                    <a href="/tags/Java/">
                        <span class="chip bg-color">Java</span>
                    </a>
                    
                    <a href="/tags/Algorithm/">
                        <span class="chip bg-color">Algorithm</span>
                    </a>
                    
                    <a href="/tags/DataStructure/">
                        <span class="chip bg-color">DataStructure</span>
                    </a>
                    
                </div>
                
            </div>
        </div>
        
        
        <div class="article col s12 m6" data-aos="fade-up">
            <div class="article-badge right-badge text-color">
                下一篇&nbsp;<i class="fas fa-chevron-right"></i>
            </div>
            <div class="card">
                <a href="/posts/82bcb26d.html">
                    <div class="card-image">
                        
                        
                        <img src="/medias/featureimages/8.jpg" class="responsive-img" alt="Java8其他新特性之Optional类">
                        
                        <span class="card-title">Java8其他新特性之Optional类</span>
                    </div>
                </a>
                <div class="card-content article-content">
                    <div class="summary block-with-text">
                        
                              
引言：
空指针异常是导致Java应用程序失败的最常见原因。以前，为了解决空指针异常，Google公司著名的Guava项目引入了Optional类，Guava通过使用检查空值的方式来防止代码污染，它鼓励程序员写更干净的代码。受到Goog
                        
                    </div>
                    <div class="publish-info">
                            <span class="publish-date">
                                <i class="far fa-clock fa-fw icon-date"></i>2021-01-20
                            </span>
                        <span class="publish-author">
                            
                            <i class="fas fa-bookmark fa-fw icon-category"></i>
                            
                            <a href="/categories/Java/" class="post-category">
                                    Java
                                </a>
                            
                            
                        </span>
                    </div>
                </div>
                
                <div class="card-action article-tags">
                    
                    <a href="/tags/Java/">
                        <span class="chip bg-color">Java</span>
                    </a>
                    
                </div>
                
            </div>
        </div>
        
    </div>
</article>

</div>



<!-- 代码块功能依赖 -->
<script type="text/javascript" src="/libs/codeBlock/codeBlockFuction.js"></script>

<!-- 代码语言 -->

<script type="text/javascript" src="/libs/codeBlock/codeLang.js"></script>


<!-- 代码块复制 -->

<script type="text/javascript" src="/libs/codeBlock/codeCopy.js"></script>


<!-- 代码块收缩 -->

<script type="text/javascript" src="/libs/codeBlock/codeShrink.js"></script>


    </div>
    <div id="toc-aside" class="expanded col l3 hide-on-med-and-down">
        <div class="toc-widget card" style="background-color: white;">
            <div class="toc-title"><i class="far fa-list-alt"></i>&nbsp;&nbsp;目录</div>
            <div id="toc-content"></div>
        </div>
    </div>
</div>

<!-- TOC 悬浮按钮. -->

<div id="floating-toc-btn" class="hide-on-med-and-down">
    <a class="btn-floating btn-large bg-color">
        <i class="fas fa-list-ul"></i>
    </a>
</div>


<script src="/libs/tocbot/tocbot.min.js"></script>
<script>
    $(function () {
        tocbot.init({
            tocSelector: '#toc-content',
            contentSelector: '#articleContent',
            headingsOffset: -($(window).height() * 0.4 - 45),
            collapseDepth: Number('0'),
            headingSelector: 'h2, h3, h4'
        });

        // modify the toc link href to support Chinese.
        let i = 0;
        let tocHeading = 'toc-heading-';
        $('#toc-content a').each(function () {
            $(this).attr('href', '#' + tocHeading + (++i));
        });

        // modify the heading title id to support Chinese.
        i = 0;
        $('#articleContent').children('h2, h3, h4').each(function () {
            $(this).attr('id', tocHeading + (++i));
        });

        // Set scroll toc fixed.
        let tocHeight = parseInt($(window).height() * 0.4 - 64);
        let $tocWidget = $('.toc-widget');
        $(window).scroll(function () {
            let scroll = $(window).scrollTop();
            /* add post toc fixed. */
            if (scroll > tocHeight) {
                $tocWidget.addClass('toc-fixed');
            } else {
                $tocWidget.removeClass('toc-fixed');
            }
        });

        
        /* 修复文章卡片 div 的宽度. */
        let fixPostCardWidth = function (srcId, targetId) {
            let srcDiv = $('#' + srcId);
            if (srcDiv.length === 0) {
                return;
            }

            let w = srcDiv.width();
            if (w >= 450) {
                w = w + 21;
            } else if (w >= 350 && w < 450) {
                w = w + 18;
            } else if (w >= 300 && w < 350) {
                w = w + 16;
            } else {
                w = w + 14;
            }
            $('#' + targetId).width(w);
        };

        // 切换TOC目录展开收缩的相关操作.
        const expandedClass = 'expanded';
        let $tocAside = $('#toc-aside');
        let $mainContent = $('#main-content');
        $('#floating-toc-btn .btn-floating').click(function () {
            if ($tocAside.hasClass(expandedClass)) {
                $tocAside.removeClass(expandedClass).hide();
                $mainContent.removeClass('l9');
            } else {
                $tocAside.addClass(expandedClass).show();
                $mainContent.addClass('l9');
            }
            fixPostCardWidth('artDetail', 'prenext-posts');
        });
        
    });
</script>

    

</main>




    <footer class="page-footer bg-color">
    
        <link rel="stylesheet" href="/libs/aplayer/APlayer.min.css">
<style>
    .aplayer .aplayer-lrc p {
        
        display: none;
        
        font-size: 12px;
        font-weight: 700;
        line-height: 16px !important;
    }

    .aplayer .aplayer-lrc p.aplayer-lrc-current {
        
        display: none;
        
        font-size: 15px;
        color: #42b983;
    }

    
    .aplayer.aplayer-fixed.aplayer-narrow .aplayer-body {
        left: -66px !important;
    }

    .aplayer.aplayer-fixed.aplayer-narrow .aplayer-body:hover {
        left: 0px !important;
    }

    
</style>
<div class="">
    
    <div class="row">
        <meting-js class="col l8 offset-l2 m10 offset-m1 s12"
                   server="netease"
                   type="playlist"
                   id="7565528433"
                   fixed='true'
                   autoplay='false'
                   theme='#42b983'
                   loop='all'
                   order='random'
                   preload='auto'
                   volume='0.4'
                   list-folded='true'
        >
        </meting-js>
    </div>
</div>

<script src="/libs/aplayer/APlayer.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/meting@2/dist/Meting.min.js"></script>

    
    <div class="container row center-align" style="margin-bottom: 15px !important;">
        <div class="col s12 m8 l8 copy-right">
            Copyright&nbsp;&copy;
            
                <span id="year">2019-2024</span>
            
            <span id="year">2019</span>
            <a href="/about" target="_blank">YangChongZhi</a>
            |&nbsp;Powered by&nbsp;<a href="https://hexo.io/" target="_blank">Hexo</a>
            |&nbsp;Theme&nbsp;<a href="https://github.com/blinkfox/hexo-theme-matery" target="_blank">Matery</a>
            <br>
            
            &nbsp;<i class="fas fa-chart-area"></i>&nbsp;站点总字数:&nbsp;<span
                class="white-color">236.5k</span>&nbsp;字
            
            
            
            
            
            
            <span id="busuanzi_container_site_pv">
                |&nbsp;<i class="far fa-eye"></i>&nbsp;总访问量:&nbsp;<span id="busuanzi_value_site_pv"
                    class="white-color"></span>&nbsp;次
            </span>
            
            
            <span id="busuanzi_container_site_uv">
                |&nbsp;<i class="fas fa-users"></i>&nbsp;总访问人数:&nbsp;<span id="busuanzi_value_site_uv"
                    class="white-color"></span>&nbsp;人
            </span>
            
            <br>
            
            <span id="sitetime">载入运行时间...</span>
            <script>
                function siteTime() {
                    var seconds = 1000;
                    var minutes = seconds * 60;
                    var hours = minutes * 60;
                    var days = hours * 24;
                    var years = days * 365;
                    var today = new Date();
                    var startYear = "2019";
                    var startMonth = "6";
                    var startDate = "28";
                    var startHour = "0";
                    var startMinute = "0";
                    var startSecond = "0";
                    var todayYear = today.getFullYear();
                    var todayMonth = today.getMonth() + 1;
                    var todayDate = today.getDate();
                    var todayHour = today.getHours();
                    var todayMinute = today.getMinutes();
                    var todaySecond = today.getSeconds();
                    var t1 = Date.UTC(startYear, startMonth, startDate, startHour, startMinute, startSecond);
                    var t2 = Date.UTC(todayYear, todayMonth, todayDate, todayHour, todayMinute, todaySecond);
                    var diff = t2 - t1;
                    var diffYears = Math.floor(diff / years);
                    var diffDays = Math.floor((diff / days) - diffYears * 365);
                    var diffHours = Math.floor((diff - (diffYears * 365 + diffDays) * days) / hours);
                    var diffMinutes = Math.floor((diff - (diffYears * 365 + diffDays) * days - diffHours * hours) /
                        minutes);
                    var diffSeconds = Math.floor((diff - (diffYears * 365 + diffDays) * days - diffHours * hours -
                        diffMinutes * minutes) / seconds);
                    if (startYear == todayYear) {
                        document.getElementById("year").innerHTML = todayYear;
                        document.getElementById("sitetime").innerHTML = "本站已安全运行 " + diffDays + " 天 " + diffHours +
                            " 小时 " + diffMinutes + " 分钟 " + diffSeconds + " 秒";
                    } else {
                        document.getElementById("year").innerHTML = startYear + " - " + todayYear;
                        document.getElementById("sitetime").innerHTML = "本站已安全运行 " + diffYears + " 年 " + diffDays +
                            " 天 " + diffHours + " 小时 " + diffMinutes + " 分钟 " + diffSeconds + " 秒";
                    }
                }
                setInterval(siteTime, 1000);
            </script>
            
            <br>
            
            <span id="icp"><img src="/medias/icp.png" style="vertical-align: text-bottom;" />
                <a href="http://beian.miit.gov.cn/" target="_blank">渝ICP备2021001798号-1</a>
            </span>
            
        </div>
        <div class="col s12 m4 l4 social-link social-statis">
    <a href="https://github.com/yczlab" class="tooltipped" target="_blank" data-tooltip="访问我的GitHub" data-position="top" data-delay="50">
        <i class="fab fa-github"></i>
    </a>



    <a href="https://gitee.com/yczlab" class="tooltipped" target="_blank" data-tooltip="访问我的码云" data-position="top" data-delay="50">
        <i class="fab fa-github"></i>
    </a>



    <a href="mailto:2685733832@qq.com" class="tooltipped" target="_blank" data-tooltip="邮件联系我" data-position="top" data-delay="50">
        <i class="fas fa-envelope-open"></i>
    </a>







    <a href="tencent://AddContact/?fromId=50&fromSubId=1&subcmd=all&uin=2685733832" class="tooltipped" target="_blank" data-tooltip="QQ联系我: 2685733832" data-position="top" data-delay="50">
        <i class="fab fa-qq"></i>
    </a>



    <a href="tencent://AddContact/?fromId=50&fromSubId=1&subcmd=all&uin=2685733832" class="tooltipped" target="_blank" data-tooltip="微信联系我: yczlab" data-position="top" data-delay="50">
        <i class="fab fa-weixin"></i>
    </a>



    <a href="https://weibo.com/yczlab" class="tooltipped" target="_blank" data-tooltip="关注我的微博: https://weibo.com/yczlab" data-position="top" data-delay="50">
        <i class="fab fa-weibo"></i>
    </a>



    <a href="https://www.zhihu.com/people/yczlab" class="tooltipped" target="_blank" data-tooltip="关注我的知乎: https://www.zhihu.com/people/yczlab" data-position="top" data-delay="50">
        <i class="fab fa-zhihu1">知</i>
    </a>



</div>
    </div>
</footer>

<div class="progress-bar"></div>


    <!-- 搜索遮罩框 -->
<div id="searchModal" class="modal">
    <div class="modal-content">
        <div class="search-header">
            <span class="title"><i class="fas fa-search"></i>&nbsp;&nbsp;搜索</span>
            <input type="search" id="searchInput" name="s" placeholder="请输入搜索的关键字"
                   class="search-input">
        </div>
        <div id="searchResult"></div>
    </div>
</div>

<script type="text/javascript">
$(function () {
    var searchFunc = function (path, search_id, content_id) {
        'use strict';
        $.ajax({
            url: path,
            dataType: "xml",
            success: function (xmlResponse) {
                // get the contents from search data
                var datas = $("entry", xmlResponse).map(function () {
                    return {
                        title: $("title", this).text(),
                        content: $("content", this).text(),
                        url: $("url", this).text()
                    };
                }).get();
                var $input = document.getElementById(search_id);
                var $resultContent = document.getElementById(content_id);
                $input.addEventListener('input', function () {
                    var str = '<ul class=\"search-result-list\">';
                    var keywords = this.value.trim().toLowerCase().split(/[\s\-]+/);
                    $resultContent.innerHTML = "";
                    if (this.value.trim().length <= 0) {
                        return;
                    }
                    // perform local searching
                    datas.forEach(function (data) {
                        var isMatch = true;
                        var data_title = data.title.trim().toLowerCase();
                        var data_content = data.content.trim().replace(/<[^>]+>/g, "").toLowerCase();
                        var data_url = data.url;
                        data_url = data_url.indexOf('/') === 0 ? data.url : '/' + data_url;
                        var index_title = -1;
                        var index_content = -1;
                        var first_occur = -1;
                        // only match artiles with not empty titles and contents
                        if (data_title !== '' && data_content !== '') {
                            keywords.forEach(function (keyword, i) {
                                index_title = data_title.indexOf(keyword);
                                index_content = data_content.indexOf(keyword);
                                if (index_title < 0 && index_content < 0) {
                                    isMatch = false;
                                } else {
                                    if (index_content < 0) {
                                        index_content = 0;
                                    }
                                    if (i === 0) {
                                        first_occur = index_content;
                                    }
                                }
                            });
                        }
                        // show search results
                        if (isMatch) {
                            str += "<li><a href='" + data_url + "' class='search-result-title'>" + data_title + "</a>";
                            var content = data.content.trim().replace(/<[^>]+>/g, "");
                            if (first_occur >= 0) {
                                // cut out 100 characters
                                var start = first_occur - 20;
                                var end = first_occur + 80;
                                if (start < 0) {
                                    start = 0;
                                }
                                if (start === 0) {
                                    end = 100;
                                }
                                if (end > content.length) {
                                    end = content.length;
                                }
                                var match_content = content.substr(start, end);
                                // highlight all keywords
                                keywords.forEach(function (keyword) {
                                    var regS = new RegExp(keyword, "gi");
                                    match_content = match_content.replace(regS, "<em class=\"search-keyword\">" + keyword + "</em>");
                                });

                                str += "<p class=\"search-result\">" + match_content + "...</p>"
                            }
                            str += "</li>";
                        }
                    });
                    str += "</ul>";
                    $resultContent.innerHTML = str;
                });
            }
        });
    };

    searchFunc('/search.xml', 'searchInput', 'searchResult');
});
</script>

    <!-- 回到顶部按钮 -->
<div id="backTop" class="top-scroll">
    <a class="btn-floating btn-large waves-effect waves-light" href="#!">
        <i class="fas fa-arrow-up"></i>
    </a>
</div>


    <script src="/libs/materialize/materialize.min.js"></script>
    <script src="/libs/masonry/masonry.pkgd.min.js"></script>
    <script src="/libs/aos/aos.js"></script>
    <script src="/libs/scrollprogress/scrollProgress.min.js"></script>
    <script src="/libs/lightGallery/js/lightgallery-all.min.js"></script>
    <script src="/js/matery.js"></script>

    <!-- Baidu Analytics -->

    <!-- Baidu Push -->

<script>
    (function () {
        var bp = document.createElement('script');
        var curProtocol = window.location.protocol.split(':')[0];
        if (curProtocol === 'https') {
            bp.src = 'https://zz.bdstatic.com/linksubmit/push.js';
        } else {
            bp.src = 'http://push.zhanzhang.baidu.com/push.js';
        }
        var s = document.getElementsByTagName("script")[0];
        s.parentNode.insertBefore(bp, s);
    })();
</script>

    
    <script src="/libs/others/clicklove.js" async="async"></script>
    
    
    <script async src="/libs/others/busuanzi.pure.mini.js"></script>
    

    
        <script src="//code.tidio.co/ef3vil8uaqrvp7giqeg545xldzmymqss.js"></script>
    

    

	
    
    <script type="text/javascript" color="0,0,255"
        pointColor="0,0,255" opacity='0.5'
        zIndex="-1" count="99"
        src="/libs/background/canvas-nest.js"></script>
    

    
    
    <script type="text/javascript" size="150" alpha='0.6'
        zIndex="-1" src="/libs/background/ribbon-refresh.min.js" async="async"></script>
    

    
    <script type="text/javascript" src="/libs/background/ribbon-dynamic.js" async="async"></script>
    

    
    <script src="/libs/instantpage/instantpage.js" type="module"></script>
    
	
	<script type="text/javascript">
	var OriginTitile = document.title,st;
	document.addEventListener("visibilitychange", function () {
		document.hidden ? (document.title = "Σ(っ °Д °;)っ我隐藏了！", clearTimeout(st)) : (document.title="(๑•̀ㅂ•́) ✧被发现了！", st=setTimeout(function () {document.title = OriginTitile}, 3e3))
	});
	</script>
	
	<!-- 背景樱花飘落特效 -->
	
	
	<!-- 背景雪花飘落特效 -->
	
	
	<!-- 数字雨特效 -->
	
		<script type="text/javascript">
		//只在桌面版网页启用特效
		var windowWidth = $(window).width();
		if (windowWidth > 768) {
			document.write('<canvas id="digitalrain" width="1440" height="900" style="position:fixed; z-index:-2; right:0px; bottom:0px; min-width:100%; min-height:100%; height:auto; width:auto;"><\/canvas>');
			document.write('<script type="text/javascript" src="/js/digitalrain.js"><\/script>');
		}
		</script>
	

</body>

</html>
